# -*- coding:utf-8 -*-

from . import project
from flask import render_template,request,flash,redirect,url_for,make_response,session
from admin_model import User,db,Role
from flask_wtf.csrf import generate_csrf
@project.route('/register',methods=['POST','GET'])
def register():
    if request.method == "POST":
        user=request.form.get('userName')
        pwd1=request.form.get('userPwd1')
        pwd2=request.form.get('userPwd2')

        if not all([user,pwd1,pwd2]):
            flash("注册参数不完整")
            token = generate_csrf()
            response = make_response(render_template('register.html', token=token))
            response.set_cookie('csrf_token', token)
            return response
        if pwd2 != pwd1:
            flash("两次密码不一致")
            token = generate_csrf()
            response = make_response(render_template('register.html', token=token))
            response.set_cookie('csrf_token', token)
            return response

        user_list=User.query.filter_by(name=user).all()
        role=Role.query.all()[0]

        if user_list == []:
            user=User(name=user,pwd=pwd2,roles_id=role.id)
            db.session.add(user)
            db.session.commit()
            flash('注册成功！')
            session['user_id']=user.id
            return redirect(url_for('project_1.index'))
        else:
            flash('用户名已注册请登录')
            token = generate_csrf()
            response = make_response(render_template('register.html', token=token))
            response.set_cookie('csrf_token', token)
            return response
    elif request.method == "GET":
        token = generate_csrf()
        response = make_response(render_template('register.html', token=token))
        response.set_cookie('csrf_token', token)
        return response